import cv2

def save():
    cap = cv2.VideoCapture(0)

    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1024)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 768)

    fourcc_i420 = cv2.VideoWriter_fourcc(*'I420')
    fourcc_xvid = cv2.VideoWriter_fourcc(*'XVID')
    fourcc_mp4v = cv2.VideoWriter_fourcc(*'mp4v')

    out_i420 = cv2.VideoWriter('8/output_i420.avi', fourcc_i420, 20.0, (1024, 768), isColor=False)
    out_xvid = cv2.VideoWriter('8/output_xvid.avi', fourcc_xvid, 20.0, (1024, 768), isColor=False)
    out_mp4v = cv2.VideoWriter('8/output_mp4v.mp4', fourcc_mp4v, 20.0, (1024, 768), isColor=False)

    while True:
        ret, frame = cap.read()

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        blurred = cv2.GaussianBlur(gray, (5, 5), 0)

        # 自适应阈值（高斯加权，增强面部特征）
        binary = cv2.adaptiveThreshold(
            blurred, 
            255,  # 最大值
            cv2.ADAPTIVE_THRESH_GAUSSIAN_C,  # 高斯加权
            cv2.THRESH_BINARY_INV,  # 反向二值化（更易看清面部）
            51,   # 邻域大小（奇数，越大越平滑）
            10    # 常数调整（影响对比度）
        )
        
        out_i420.write(binary)
        out_mp4v.write(binary)
        out_xvid.write(binary)

        cv2.imshow('frame', binary)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    out_i420.release()
    out_xvid.release()
    out_mp4v.release()
    cv2.destroyAllWindows()

def main():
    save()

if __name__ == '__main__':
    main()